package com.adu.music.parser;

import com.adu.music.bean.Proxy;
import com.adu.music.util.CommonUtils;
import com.adu.music.util.JsoupUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author duchuanchuan
 * @date 2017/1/5
 */
public class KuaidailiParser implements ProxyParser {

    private static final Logger logger = LoggerFactory.getLogger(KuaidailiParser.class);

    private List<Proxy> parseByIndex(int index, List<Proxy> proxyList) {
        String url = "http://www.kuaidaili.com/proxylist/" + index + "/";
        try {
            Document doc = JsoupUtils.connectWithBaseHeaders(url).get();
            Elements trs = doc.select("#index_free_list tbody tr");
            logger.info("第{}页有{}个代理", index, trs.size());
            if (trs.size() > 0) {
                trs.forEach(tr -> {
                    Elements tds = tr.getElementsByTag("td");
                    if (tds.size() > 0) {
                        String ip = tds.get(0).text();
                        int port = CommonUtils.parseInt(tds.get(1).text());
                        String anonymous = tds.get(2).text();
                        String type = tds.get(3).text();
                        String getpost = tds.get(4).text();
                        String speedStr = StringUtils.substringBefore(tds.get(6).text(), "秒");
                        double speed = Double.parseDouble(speedStr);
                        Proxy proxy = new Proxy(ip, port, type, getpost, speed);
                        logger.info("获取到代理:{}:{},{},{},等级{}", ip, port, anonymous, speed, proxy.getPriority());
                        proxyList.add(proxy);
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return proxyList;
    }

    @Override
    public List<Proxy> parseProxyList() {
        List<Proxy> proxyList = new ArrayList<>(112);
        for (int i = 1; i <= 10; i++) {
            parseByIndex(i, proxyList);
        }
        return proxyList;
    }
}
